#include "stdafx.h"
#include "VertexBuffer.h"


CVertexBuffer::CVertexBuffer(uint length, bool dynamic)
: m_pVB(nullptr)
, m_pLockData(nullptr)
, m_length(length)
, m_bDynamic(dynamic)
{
	ulong usage = dynamic ? D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY : 0;

	HRESULT hr = g_pDevice->CreateVertexBuffer(length, usage, 0, D3DPOOL_DEFAULT, &m_pVB, nullptr);
	assert(hr == D3D_OK);
}

CVertexBuffer::~CVertexBuffer()
{
	SAFE_RELEASE(m_pVB);
}

void*	CVertexBuffer::Lock(uint offset, uint size, EVertexBufferLockType lock_type)
{
	assert(offset + size <= m_length);

	uint flags = 0;
	switch (lock_type)
	{
	case eVBLock_Discard:
		assert(offset == 0 && (size == m_length || size == 0));	//	all buffer discarded
		flags = m_bDynamic ? D3DLOCK_DISCARD : 0;
		break;

	case eVBLock_NoOverwrite:
		assert(m_bDynamic);
		flags = D3DLOCK_NOOVERWRITE;
		break;

	case eVBLock_ReadOnly:
		assert(!m_bDynamic);	//	reading denied from dynamic buffers
		flags = D3DLOCK_READONLY;
		break;
	}

	HRESULT hr = m_pVB->Lock(offset, size, &m_pLockData, flags);
	assert(hr == D3D_OK);

	return m_pLockData;
}

void CVertexBuffer::Unlock()
{
	HRESULT hr = m_pVB->Unlock();
	assert(hr == D3D_OK);

	m_pLockData = nullptr;
}

uint CVertexBuffer::GetSize() const
{
	return m_length;
}

CVertexBuffer::operator IDirect3DVertexBuffer9* () const
{
	return m_pVB;
}